package com.sgzn.sgpay.service.impl;

import com.sgzn.sgpay.enums.SgsResponseCode;
import com.sgzn.sgpay.exception.SgpayException;
import com.sgzn.sgpay.model.request.SgsUserUpdateRequest;
import com.sgzn.sgpay.model.response.SgsResultResponse;
import com.sgzn.sgpay.persistence.dao.TUserMapper;
import com.sgzn.sgpay.persistence.domain.TUser;
import com.sgzn.sgpay.persistence.domain.TUserExample;
import com.sgzn.sgpay.service.SgsUserService;
import com.sgzn.sgpay.service.support.SgsResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户信息管理接口
 * @author zhongzhongyong
 * @version Id: SgsLoginServiceImpl.java, v 0.1 2018/4/5 14:06 zhongzhongyong Exp $$
 */
@Service
@Slf4j
public class SgsUserServiceImpl implements SgsUserService {

    @Autowired
    private TUserMapper tUserMapper;

    @Override
    @Transactional(readOnly = false, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public SgsResultResponse<String> update(SgsUserUpdateRequest request) {
        try {
            String userId = request.getUserId();
            TUser record = new TUser();
            record.setUserName(request.getUserName());
            TUserExample example = new TUserExample();
            TUserExample.Criteria criteria =example.createCriteria();
            criteria.andUserIdEqualTo(userId);
            int result = tUserMapper.updateByExampleSelective(record,example);
            if(result != 0){
                return SgsResponseUtil.INSTANCE.success("success");
            }else{
                throw new SgpayException(SgsResponseCode.C_USERNAME_UPDATE_EXCEPTION.getResponseCode(),
                        SgsResponseCode.C_USERNAME_UPDATE_EXCEPTION.getResponseCode());
            }
        } catch (SgpayException e){
            log.error("occur SgpayException : {},{}",e.getCode(),e.getDesc());
            return SgsResponseUtil.INSTANCE.fail(e.getCode(),e.getDesc());
        } catch (Exception e) {
            log.error("occur Exception : {},{}",SgsResponseCode.C503000.getResponseCode(),
                    SgsResponseCode.C503000.getResponseDesc());
            return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C503000.getResponseCode(),
                    SgsResponseCode.C503000.getResponseDesc());
        }
    }
}
